package com.aitaoxue.palx;

import io.rong.imkit.RongIM;

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.aitaoxue.palx.api.ApiHttpClient;
import com.aitaoxue.palx.base.BaseApplication;
import com.aitaoxue.palx.db.GoodDBHelper;
import com.aitaoxue.palx.db.InfoDBHelper;
import com.aitaoxue.palx.db.RongyunContext;
import com.aitaoxue.palx.db.course.CourseContext;
import com.aitaoxue.palx.im.message.PushMessage;
import com.aitaoxue.palx.util.StringUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.process.BitmapProcessor;

/**
 * 应用application 提供data/file目录下数据存取的静态方法
 * 
 * @author earthgee
 * 
 */
public class AppContext extends BaseApplication {

	private static final String TAG = AppContext.class.getSimpleName();

	public static final int PAGE_SIZE = 20;
	private static final int CACHE_TIME = 60 * 60000;

	private static AppContext instance;

	/**
	 * 初始化异常处理
	 * 
	 */
	@Override
	public void onCreate() {
		super.onCreate();

		if ("com.aitaoxue.palx"
				.equals(getCurProcessName(getApplicationContext()))) {
			try {
				Class.forName("android.os.AsyncTask");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Thread.setDefaultUncaughtExceptionHandler(AppException
					.getAppExceptionHandler(this));
			instance = this;

			JPushInterface.init(this);

			initImageLoader(this);
			
			init();
		}

		// 初始化即时通信
		initRongyun();
	}

	private void init() {
		AsyncHttpClient client = new AsyncHttpClient();
		PersistentCookieStore mCookieStore = new PersistentCookieStore(this);
		client.setCookieStore(mCookieStore);
		ApiHttpClient.setHttpClient(client);
		initConfigDir();
		
		CourseContext.init(this);
	}

	private void initRongyun() {
		if ("com.aitaoxue.palx"
				.equals(getCurProcessName(getApplicationContext()))
				|| "io.rong.push"
						.equals(getCurProcessName(getApplicationContext()))) {

			RongIM.init(this);

			if ("com.aitaoxue.palx"
					.equals(getCurProcessName(getApplicationContext()))) {

				RongCloudEvent.init(this);
				RongyunContext.init(this);
			}
		}
	}

	private void initConfigDir() {
		File dirpath = getDir(AppConfig.APP_CONFIG, Context.MODE_PRIVATE);
		File file = new File(dirpath, AppConfig.APP_CONFIG);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void initImageLoader(Context context) {
		DisplayImageOptions displayOptions = new DisplayImageOptions.Builder()
				.preProcessor(new BitmapProcessor() {

					@Override
					public Bitmap process(Bitmap source) {
						return source;
					}
				}).cacheInMemory(true).cacheOnDisk(true)
				.bitmapConfig(Config.ARGB_8888).build();

		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.diskCacheSize(50 * 1024 * 1024)
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs().defaultDisplayImageOptions(displayOptions)
				.build();

		ImageLoader.getInstance().init(config);

	}

	/**
	 * 获得Context
	 * 
	 * @return AppContext
	 */
	public static AppContext getInstance() {
		return instance;
	}

	/**
	 * 检查是否包含属性
	 * 
	 * @param key
	 * @return
	 */
	public boolean containsProperty(String key) {
		Properties props = getProperties();
		return props.containsKey(key);
	}

	/**
	 * 
	 * 
	 * @param ps
	 */
	public void setProperties(Properties ps) {
		AppConfig.getAppConfig(this).set(ps);
	}

	public void setProperty(String key, String value) {
		AppConfig.getAppConfig(this).set(key, value);
	}

	public String getProperty(String key) {
		String res = AppConfig.getAppConfig(this).get(key);
		return res;
	}

	public void removeProperty(String... key) {
		AppConfig.getAppConfig(this).remove(key);
	}

	public Properties getProperties() {
		return AppConfig.getAppConfig(this).get();
	}

	public String getAppId() {
		String uniqueID = getProperty(AppConfig.CONF_APP_UNIQUEID);
		if (StringUtils.isEmpty(uniqueID)) {
			uniqueID = UUID.randomUUID().toString();
			setProperty(AppConfig.CONF_APP_UNIQUEID, uniqueID);
		}
		return uniqueID;
	}

	/**
	 * 获得packageInfo信息
	 * 
	 * @return PackageInfo
	 */
	public PackageInfo getPackageInfo() {
		PackageInfo info = null;
		try {
			info = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace(System.err);
		}
		if (info == null)
			info = new PackageInfo();
		return info;
	}

	public static String getCurProcessName(Context context) {
		int pid = android.os.Process.myPid();

		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningAppProcessInfo appProcess : activityManager
				.getRunningAppProcesses()) {
			if (appProcess.pid == pid) {
				return appProcess.processName;
			}
		}

		return null;
	}
}
